<template>
  <div class="scrap-management">
    <!-- 报废信息展示 -->
    <div class="header">
      <h2>设备报废管理</h2>
      <el-button type="primary" @click="showDialog">新增报废申请</el-button>
    </div>

    <!-- 报废信息表格 -->
    <el-table :data="scrapList" style="width: 100%" border>
      <el-table-column prop="scrapId" label="报废单号" width="180" />
      <el-table-column prop="equipmentId" label="设备编号" width="150" />
      <el-table-column prop="equipmentName" label="设备名称" width="150" />
      <el-table-column prop="equipmentType" label="设备类型" width="120" />
      <el-table-column prop="department" label="所属部门" width="120" />
      <el-table-column prop="scrapReason" label="报废原因" width="200" />
      <el-table-column prop="applicant" label="申请人" width="100" />
      <el-table-column prop="applyDate" label="申请日期" width="120" />
      <el-table-column label="状态" width="120">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ row.status }}
          </el-tag>
          <el-button
              v-if="row.status === '未通过'"
              type="text"
              @click="showReason(row)"
          >
            查看原因
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="{ row }">
          <el-button
              v-if="row.status === '待审批'"
              type="success"
              size="small"
              @click="approveScrap(row, '通过')"
          >
            通过
          </el-button>
          <el-button
              v-if="row.status === '待审批'"
              type="danger"
              size="small"
              @click="showRejectDialog(row)"
          >
            驳回
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 报废申请对话框 -->
    <el-dialog v-model="dialogVisible" title="设备报废申请" width="600px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="报废单号">
          <el-input v-model="form.scrapId" disabled />
        </el-form-item>
        <el-form-item label="设备编号" prop="equipmentId">
          <el-input v-model="form.equipmentId" />
        </el-form-item>
        <el-form-item label="设备名称" prop="equipmentName">
          <el-input v-model="form.equipmentName" />
        </el-form-item>
        <el-form-item label="设备类型" prop="equipmentType">
          <el-select v-model="form.equipmentType" placeholder="请选择">
            <el-option
                v-for="item in equipmentTypes"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属部门" prop="department">
          <el-select v-model="form.department" placeholder="请选择">
            <el-option
                v-for="item in departments"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="报废原因" prop="scrapReason">
          <el-select v-model="form.scrapReason" placeholder="请选择">
            <el-option
                v-for="item in scrapReasons"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="详细说明">
          <el-input
              v-model="form.description"
              type="textarea"
              :rows="3"
              placeholder="请详细说明报废原因（选填）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </template>
    </el-dialog>

    <!-- 驳回原因对话框 -->
    <el-dialog v-model="rejectDialogVisible" title="驳回原因" width="500px">
      <el-input
          v-model="rejectReason"
          type="textarea"
          :rows="4"
          placeholder="请输入驳回原因"
      />
      <template #footer>
        <el-button @click="rejectDialogVisible = false">取消</el-button>
        <el-button
            type="primary"
            @click="approveScrap(currentScrap, '未通过', rejectReason)"
        >
          确认
        </el-button>
      </template>
    </el-dialog>

    <!-- 原因查看对话框 -->
    <el-dialog v-model="reasonDialogVisible" title="驳回原因" width="500px">
      <div>{{ currentReason }}</div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'

interface ScrapItem {
  scrapId: string
  equipmentId: string
  equipmentName: string
  equipmentType: string
  department: string
  scrapReason: string
  description?: string
  applicant: string
  applyDate: string
  status: '待审批' | '通过' | '未通过'
  reason?: string
}

// 报废列表数据
const scrapList = ref<ScrapItem[]>([
  {
    scrapId: 'BF202310001',
    equipmentId: 'EQ10001',
    equipmentName: 'Dell服务器R740',
    equipmentType: '服务器',
    department: '信息技术部',
    scrapReason: '设备老化',
    applicant: '张伟',
    applyDate: '2023-10-15',
    status: '待审批'
  }
])

// 表单相关
const formRef = ref()
const dialogVisible = ref(false)
const form = reactive({
  scrapId: '',
  equipmentId: '',
  equipmentName: '',
  equipmentType: '',
  department: '',
  scrapReason: '',
  description: ''
})

// 审批相关
const rejectDialogVisible = ref(false)
const reasonDialogVisible = ref(false)
const currentScrap = ref<ScrapItem | null>(null)
const currentReason = ref('')
const rejectReason = ref('')

// 选项数据
const equipmentTypes = [
  { value: 'server', label: '服务器' },
  { value: 'network', label: '网络设备' },
  { value: 'storage', label: '存储设备' },
  { value: 'safety', label: '安全设备' }
]

const departments = [
  { value: 'it', label: '信息技术部' },
  { value: 'rd', label: '研发部' },
  { value: 'production', label: '生产部' }
]

const scrapReasons = [
  { value: 'equipment_aging', label: '设备老化' },
  { value: 'technical_obsolescence', label: '技术淘汰' },
  { value: 'irreparable', label: '无法修复' },
  { value: 'economy_inefficient', label: '经济不划算' }
]

// 表单验证规则
const rules = {
  equipmentId: [{ required: true, message: '请输入设备编号', trigger: 'blur' }],
  equipmentName: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
  equipmentType: [{ required: true, message: '请选择设备类型', trigger: 'change' }],
  department: [{ required: true, message: '请选择所属部门', trigger: 'change' }],
  scrapReason: [{ required: true, message: '请选择报废原因', trigger: 'change' }]
}

// 生成报废单号
const generateScrapId = () => {
  const date = new Date()
  const year = date.getFullYear()
  const month = (date.getMonth() + 1).toString().padStart(2, '0')
  const day = date.getDate().toString().padStart(2, '0')
  const random = Math.floor(Math.random() * 900 + 100)
  return `BF${year}${month}${day}${random}`
}

// 显示新增对话框
const showDialog = () => {
  form.scrapId = generateScrapId()
  dialogVisible.value = true
}

// 提交表单
const submitForm = () => {
  formRef.value.validate(valid => {
    if (valid) {
      const currentDate = new Date().toISOString().split('T')[0]
      scrapList.value.unshift({
        ...form,
        applicant: '当前用户', // 实际项目中应从用户信息获取
        applyDate: currentDate,
        status: '待审批'
      })
      ElMessage.success('报废申请已提交')
      dialogVisible.value = false
    }
  })
}

// 审批操作
const approveScrap = (item: ScrapItem, status: '通过' | '未通过', reason?: string) => {
  item.status = status
  if (status === '未通过') {
    item.reason = reason
  }
  ElMessage.success(`已${status}该申请`)
  rejectDialogVisible.value = false
}

// 显示驳回原因输入框
const showRejectDialog = (item: ScrapItem) => {
  currentScrap.value = item
  rejectReason.value = ''
  rejectDialogVisible.value = true
}

// 显示驳回原因
const showReason = (item: ScrapItem) => {
  currentReason.value = item.reason || ''
  reasonDialogVisible.value = true
}

// 状态标签样式
const getStatusType = (status: string) => {
  switch (status) {
    case '待审批': return 'warning'
    case '通过': return 'success'
    case '未通过': return 'danger'
    default: return 'info'
  }
}
</script>

<style scoped>
.scrap-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.el-table {
  margin-top: 20px;
}

.el-dialog {
  .el-select {
    width: 100%;
  }
}
</style>